package com.link.play.fit.ai.ui.scanFood

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.hardware.camera2.CameraMetadata.FLASH_MODE_OFF
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia.Companion.isPhotoPickerAvailable
import androidx.camera.core.ImageCapture.FLASH_MODE_ON
import androidx.core.app.ActivityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.bean.ScanBean
import com.link.play.fit.ai.databinding.AcScanFoodBinding
import com.link.play.fit.ai.ext.checkPermissions
import com.link.play.fit.ai.ext.launchContract
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.utils.LogX
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream

class ScanFoodAc : BaseActivity<AcScanFoodBinding>(AcScanFoodBinding::inflate) {

    private var scanBean = ScanBean()

    private val qrImageAnalyzer: QRImageAnalyzer = QRImageAnalyzer()
    private var cameraUtils: CameraUtils = CameraUtils(this)

    override fun useDefaultImmersive() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            binding.clTop.setPadding(0, systemBars.top, 0, 0)
            insets
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        binding.previewView.post {
            if (checkCameraPermission()) {
                initCamera()
            } else {
                lifecycleScope.launch {
                    val flag = checkPermissions(Manifest.permission.CAMERA)
                    if (flag) {
                        initCamera()
                    }
                }
            }
        }


        binding.ivClose.setOnClickListener {
            finish()
        }
        binding.llScanFood.setOnClickListener {
            binding.llScanFood.isSelected = true
            binding.llBarcode.isSelected = false
            binding.llFoodLabel.isSelected = false
            binding.llGallery.isSelected = false
            changeUI(0)
            scanBean.type = 0
        }
        binding.llScanFood.callOnClick()
        binding.llBarcode.setOnClickListener {
            binding.llScanFood.isSelected = false
            binding.llBarcode.isSelected = true
            binding.llFoodLabel.isSelected = false
            binding.llGallery.isSelected = false
            changeUI(1)
            scanBean.type = 1
        }
        binding.llFoodLabel.setOnClickListener {
            binding.llScanFood.isSelected = false
            binding.llBarcode.isSelected = false
            binding.llFoodLabel.isSelected = true
            binding.llGallery.isSelected = false
            changeUI(2)
            scanBean.type = 2
        }
        binding.llGallery.setOnClickListener {
            binding.llScanFood.isSelected = false
            binding.llBarcode.isSelected = false
            binding.llFoodLabel.isSelected = false
            binding.llGallery.isSelected = true
            safPickImage()
        }
        binding.ivPaiZhao.setOnClickListener {
            //EventUtils.event("ScanFood")
            qrImageAnalyzer.imageAction = { bitmap ->

                if (bitmap != null) {
                    runOnUiThread {
                        binding.ivPreview.visibility = View.VISIBLE
                        binding.ivPreview.setImageBitmap(bitmap)

                    }

                    lifecycleScope.launch(Dispatchers.IO) {

                        val file =
                            File(this@ScanFoodAc.cacheDir, "${System.currentTimeMillis()}.jpg")
                        val flag = saveBitmapToFile(bitmap, file.absolutePath)
                        if (flag) {
                            scanBean.imagePathOrUri = file.absolutePath
                        }
                        launch(Dispatchers.Main) {
                            goToAc(MainAc::class.java) {
                                putExtra("ScanBean", Gson().toJson(scanBean))
                                addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                            }
                            finish()
                        }
                    }
                }

            }
        }

    }

    override fun onResume() {
        super.onResume()
    }

    private fun saveBitmapToFile(bitmap: Bitmap, filePath: String): Boolean {
        val file = File(filePath)
        if (!file.exists()) file.createNewFile()
        return try {
            FileOutputStream(file).use { fos ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.flush()
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    private fun safPickImage() {

        lifecycleScope.launch {
            val uri =
                if (isPhotoPickerAvailable(this@ScanFoodAc) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    launchContract(
                        ActivityResultContracts.PickVisualMedia(),
                        PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
                    )

                } else {
                    val safIntent = Intent(Intent.ACTION_OPEN_DOCUMENT)
                    safIntent.addCategory(Intent.CATEGORY_OPENABLE)
                    safIntent.setType("image/*")

                    val activityResult = launchContract(
                        ActivityResultContracts.StartActivityForResult(),
                        safIntent,
                    )
                    activityResult.data?.data
                }
            LogX.e(TAG, "uri=${uri.toString()}")
            if (uri == null) return@launch
            this@ScanFoodAc.contentResolver.takePersistableUriPermission(
                uri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION
            )
            scanBean.type = 3
            scanBean.imagePathOrUri = uri.toString()
            goToAc(MainAc::class.java) {
                putExtra("ScanBean", Gson().toJson(scanBean))
                addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }

        }
    }

    private fun checkCameraPermission(): Boolean {
        return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.CAMERA
        )
    }

    /**
     * 初始化相机
     */
    private fun initCamera() {
        Log.e(TAG, "initCamera")
        val hasFlash = packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)
        if (!hasFlash) {
            binding.ivFlash.visibility = View.GONE
        }

        qrImageAnalyzer.parseAction = { qrCodeValue, valueType ->
//            handleScan(qrCodeValue, valueType)
            scanBean.barcode = qrCodeValue
            scanBean.barcodeType = valueType
        }

        cameraUtils.cameraReadyCallBack = {
            Log.e(TAG, "cameraReadyCallBack")

            //闪光灯
            cameraUtils.getFlashState()?.observe(this) { state ->
                if (state == FLASH_MODE_OFF) {
                    binding.ivFlash.setImageResource(R.mipmap.icon_shanguangdeng_guan)
                    binding.ivFlash.setOnClickListener {
                        cameraUtils.turnOnFlash()
                    }
                }
                if (state == FLASH_MODE_ON) {
                    binding.ivFlash.setImageResource(R.mipmap.icon_shanguangdeng_yikai)
                    binding.ivFlash.setOnClickListener {
                        cameraUtils.turnOffFlash()
                    }
                }
            }
        }

        cameraUtils.startBind(binding.previewView, qrImageAnalyzer)
        Log.e(TAG, "startBind")
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraUtils.onDestroy()
    }

    private fun changeUI(type: Int) {

        when (type) {
            0 -> {
                binding.ivScan.visibility = View.VISIBLE
                binding.vBg.visibility = View.GONE
                binding.llBarcodeScan.visibility = View.GONE
            }

            1 -> {
                binding.ivScan.visibility = View.GONE
                binding.vBg.visibility = View.VISIBLE
                binding.llBarcodeScan.visibility = View.VISIBLE
            }

            2 -> {
                binding.ivScan.visibility = View.VISIBLE
                binding.vBg.visibility = View.GONE
                binding.llBarcodeScan.visibility = View.GONE
            }
        }

    }


}